package com.example.ormsqlsplicingframe1.proxy;


import com.example.ormsqlsplicingframe1.utlis.CopyUtils;
import com.example.ormsqlsplicingframe1.utlis.ProxySessionUtils;
import com.example.ormsqlsplicingframe1.utlis.ProxyUtil;
import lombok.SneakyThrows;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class SyncProxy implements MethodInterceptor {

     //拷贝的对象
    private Object data;

    //使用set次数
    private int size;

     //原生数据源
    private Object target;

    //代理对象
    private Object proxy;

    @SneakyThrows
    public SyncProxy(Object target) {
        this.target = target;
        this.data = copy();
    }


    @SneakyThrows
    private Object copy(){
        Object data = CopyUtils.UpdateCopy(target, target.getClass().newInstance());
        return  data;
    }


    /**
     *
     * @param var1  当前对象
     * @param var2  当前对象方法
     * @param var3  当前对象的字段列表
     * @param var4  代理对象方法
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object var1, Method var2, Object[] var3, MethodProxy var4) throws Throwable {
        Object value = var2.invoke(target, var3);
        if (ProxySessionUtils.route().isOpenTransaction() && var2.getName().startsWith("set")){
            if (var3[0] != null){
                var4.invoke(data, var3);
                size++;
            }
        }
        return value;
    }

    @SneakyThrows
    public Object getProxyInstance(){



        if(proxy != null){
            return proxy;
        }
        Class clazz =  ProxyUtil.getProxyClass(target.getClass());
        proxy =  ProxyUtil.getProxyInstance(clazz,this);


        String simpleName = proxy.getClass().getSimpleName();

        return proxy;

    }

    public Object getData() {
        return data;
    }

    public Object getProxy() {
        return proxy;
    }


    public int getSize() {
        return size;
    }
}
